<template>
  <div class="components-container">
    <el-card class="box-card" shadow="always">
      <div class="clearfix" slot="header">
        <b>
          <svg-icon icon-class="route"/>
          {{ menuName }}权限列表</b>
        <el-link v-if="menuType != 1" type="warning" icon="el-icon-info" :underline="false" style="margin-left: 20px">
          请点击左侧菜单列表选择类型【菜单】
        </el-link>

        <el-button  type="warning" size="mini" style="float: right;" :disabled="menuType != 1" @click="handleGenerate">生成默认权限</el-button>

      </div>
      <!-- 搜索表单 -->
      <el-form
          ref="queryForm"
          size="mini"
          :model="queryParams"
          :inline="true">
        <el-form-item>
          <el-button type="success" :disabled="disabled || isAuth('sys:permission:add')" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          <el-button type="danger" icon="el-icon-delete" :disabled="multiple || isAuth('sys:permission:delete')" @click="handleDelete">删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-input
              v-model="queryParams.description"
              placeholder="权限名称"
              clearable
              @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" :disabled="menuType != 1" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
          ref="table"
          :data="pageList"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          border
          size="mini">
        <el-table-column type="selection" width="40" align="center"/>
        <el-table-column label="权限名称" prop="description" width="120"/>
        <el-table-column label="URL权限" align="center">
          <el-table-column prop="serviceName" label="所属服务" width="100">
          </el-table-column>
          <el-table-column prop="requestMethod" label="请求方式" width="80">
          </el-table-column>
          <el-table-column prop="requestPath" label="请求路径">
          </el-table-column>
        </el-table-column>
        <el-table-column label="按钮权限" prop="btnPerm" width="180"/>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
                plain
                :disabled="isAuth('sys:permission:update')"
                @click="handleEdit(scope.row)"/>
            <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
                plain
                :disabled="isAuth('sys:permission:delete')"
                @click="handleDelete(scope.row)"/>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          v-show="pagination.total>0"
          :total="pagination.total"
          :page.sync="pagination.currentPage"
          :limit.sync="pagination.pageSize"
          :page-sizes="[2,5,10]"
          @pagination="handleQuery"
      />
      <el-dialog
          :title="dialog.title"
          :visible.sync="dialog.visible"
          width="700px">
        <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="120px">

          <el-form-item label="权限名称" prop="description">
            <el-input v-model="form.description" placeholder="请输入权限名称"/>
          </el-form-item>

          <el-form-item label="URL权限标识">
            <el-input placeholder="/api/v1/users" v-model="urlPerm.requestPath" class="input-with-select">
              <el-select v-model="urlPerm.serviceName" style="width: 130px;" slot="prepend" placeholder="所属服务"
                         clearable>
                <el-option v-for="item in microServiceList" :value="item.value" :label="item.name"/>
              </el-select>
              <el-select v-model="urlPerm.requestMethod" style="width: 120px;margin-left: 20px" slot="prepend"
                         placeholder="请求方式" clearable>
                <el-option v-for="item in requestMethodList" :value="item.value" :label="item.name"/>
              </el-select>
            </el-input>
            <el-link type="warning" v-show="urlPerm.requestMethod">
              {{ urlPerm.requestMethod }}:/{{ urlPerm.serviceName }}{{ urlPerm.requestPath }}
            </el-link>
          </el-form-item>

          <el-form-item label="按钮权限标识" prop="btnPerm">
            <el-input v-model="form.btnPerm" placeholder="sys:user:add"/>
          </el-form-item>

          <el-form-item label="排序" >
            <el-input-number v-model="form.orderNum" controls-position="right"></el-input-number>
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="dialog.visible=false">取 消</el-button>
        </div>
      </el-dialog>


      <!--  生成权限    -->
      <el-dialog title="生成默认权限" :visible.sync="generatorDialogVisible">
        <el-form :model="generatorForm" ref="generaForm" :rules="generatorRules">
          <el-form-item label="权限名称" label-width="120px" prop="description">
            <el-input placeholder="用户" v-model="generatorForm.description" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item  label="URL" label-width="120px" prop="requestPath">
            <el-input placeholder="/api/v1/users" v-model="generatorForm.requestPath" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item  label="按钮权限标识" label-width="120px" prop="btnPerm">
            <el-input placeholder="user" v-model="generatorForm.btnPerm" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="所属服务" label-width="120px" prop="serviceName">
            <el-select v-model="generatorForm.serviceName" placeholder="请选择所属服务">
              <el-option v-for="item in microServiceList" :value="item.value" :label="item.name"/>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="generatorDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleGenerateSubmit">生成</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  deletePermission,
  getPermissionPageList,
  permissionDetail,
  updatePermission,
  addPermission,
  generatorPerm
} from "@/api/system/permission";
import {listDictItemByCode,} from "@/api/system/dict/dict-item";

export default {
  name: "permission",
  data() {
    return {
      loading: false,
      ids: [],
      multiple: true,
      queryParams: {
        description: undefined,
        menuId: undefined
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      pageList: [],
      menu: {},
      dialog: {
        title: undefined,
        visible: false
      },
      form: {
        description: '',
        urlPerm: '',
        btnPerm: ''
      },
      urlPerm: {
        requestMethod: '',
        serviceName: '',
        requestPath: ''
      },
      microServiceList: [],
      requestMethodList: [],
      disabled: true,
      menuName: undefined,
      menuType: undefined,
      rules: {
        description: [
          {required: true, message: '请输入权限名称', trigger: 'blur'}
        ],
        method: [
          {required: true, message: '请选择请求方式', trigger: 'blur'}
        ]
      },
      generatorDialogVisible: false,
      generatorForm: {
        menuId: '',
        description: '',
        btnPerm: '',
        requestPath: '',
        serviceName: ''
      },
      generatorRules: {
        serviceName: [
          {required: true, message: '请选择所属服务', trigger: 'blur'}
        ],
        btnPerm: [
          {required: true, message: '请输入按钮权限标识', trigger: 'blur'}
        ],
        requestPath: [
          {required: true, message: '请输入URL', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入权限名称', trigger: 'blur'}
        ]
      },
    }
  },
  methods: {
    menuClick(row) {
      this.menuType = row.type
      //非目录的不执行
      if (this.menuType == 1) {
        this.disabled = false;
        this.menu = row;
        this.menuName = '【' + this.menu.name + '】';
        this.handleQuery();
      } else {
        this.menuName = undefined
      }
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    handleReset() {
      this.pagination = {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
      this.queryParams.name = undefined
      this.handleQuery()
    },
    handleQuery(flag) {
      this.queryParams.currentPage = this.pagination.currentPage
      this.queryParams.pageSize = this.pagination.pageSize
      this.queryParams.menuId = this.menu.menuId
      getPermissionPageList(this.queryParams).then(response => {
        this.pageList = response.data
        this.pagination.total = response.total
        this.loading = false
        if (flag) {
          this.$store.dispatch('getUserInfo').then(()=>{})
        }
      })
    },
    loadMicroServices() {
      listDictItemByCode('micro_service').then(response => {
        this.microServiceList = response.data
      })
    },
    loadRequestMethods() {
      listDictItemByCode('request_method').then(response => {
        this.requestMethodList = response.data
      })
    },
    async handleEdit(row) {
      await this.loadMicroServices();
      await this.loadRequestMethods();
      this.resetForm()
      this.dialog = {
        title: this.menuName + '编辑权限',
        visible: true
      }
      const id = row.id
      permissionDetail(id).then(response => {
        const {data} = response
        // 处理URL权限
        const urlPerm = data.urlPerm
        this.form = data
        if (urlPerm) {
          // GET:/uum-admin/api/v1/permission/*
          const permArr = urlPerm.split(':')
          const requestMethod = permArr[0]
          const serviceName = permArr[1].substring(1, permArr[1].substr(1).indexOf('/') + 1)
          const requestPath = permArr[1].substring(permArr[1].substr(1).indexOf('/') + 1)
          this.urlPerm = {
            requestMethod: requestMethod,
            serviceName: serviceName,
            requestPath: requestPath
          }
        }


      })
    },

    async handleGenerate() {
      await this.loadMicroServices();
      await this.loadRequestMethods();
      this.resetGeneratorForm()
      this.generatorDialogVisible = true
    },

    handleGenerateSubmit() {
      this.$refs['generaForm'].validate(valid => {
        if (valid) {
          this.generatorForm.menuId = this.menu.menuId
          generatorPerm(this.generatorForm).then(res => {
            if (res.status) {
              this.$message.success("生成成功")
              this.handleQuery(true);
              this.generatorDialogVisible = false
            }
          })
        }
      });

    },

    async handleAdd() {
      await this.loadMicroServices()
      await this.loadRequestMethods()
      this.resetForm()
      this.dialog = {
        title: this.menuName + '新增权限',
        visible: true
      }
    },
    handleSubmit: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.urlPerm.requestPath) {
            if (!this.urlPerm.requestMethod) {
              this.$message.warning('URL权限的请求方式不能为空')
              return false
            }
            if (!this.urlPerm.serviceName) {
              this.$message.warning('URL权限的所属服务不能为空')
              return false
            }
          }

          let requestPath = this.urlPerm.requestPath || '';
          let requestMethod = this.urlPerm.requestMethod;
          let serviceName = this.urlPerm.serviceName;

          // 两个权限必选一个，requestPath不能 /
          if (!(requestPath || this.form.btnPerm || requestPath.length > 1)) {
            this.$message.warning('请至少填写一种权限')
            return false
          }

          if (requestMethod && serviceName && requestPath) {
            this.form.urlPerm = requestMethod + ':/' + serviceName + requestPath;
          }else {
            this.form.urlPerm = ''
          }

          if (requestPath) {
            let first = requestPath.substring(0, 1);
            if (first === '/' && requestPath.length == 1) {
              this.$message.warning('URL权限标识格式有误')
            }
            //未加'/' 默认加上
            if (requestPath.length > 1 && first != '/') {
                this.form.urlPerm = this.urlPerm.requestMethod + ':/' + this.urlPerm.serviceName + '/' + this.urlPerm.requestPath;
            }
          }

          this.form.menuId = this.menu.menuId
          if (this.form.id != undefined) {
            updatePermission(this.form).then(() => {
              this.$message.success('修改成功')
              this.closeDialog()
              this.handleQuery(true)
            });
          } else {
            addPermission(this.form).then(() => {
              this.$message.success('新增成功')
              this.closeDialog()
              this.handleQuery(true)
            });
          }
        }
      })
    },

    handleDelete(row) {
      const ids = [row.id || this.ids].join(',')
      this.$confirm('确认删除已选中的数据项？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePermission(ids).then(() => {
          this.$message.success('删除成功')
          this.handleQuery(true)
        })
      }).catch(() =>
          this.$message.info('已取消删除')
      )
    },
    closeDialog() {
      this.resetForm()
      this.dialog = {
        title: undefined,
        visible: false
      }
    },
    resetForm() {
      this.form = {
        menuId: this.menu.id,
      }
      this.urlPerm = {}
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
    },

    resetGeneratorForm() {
      this.generatorForm = {}
      if (this.$refs['generaForm']) {
        this.$refs['generaForm'].resetFields()
      }
    },

    resetPermission() {
      this.disabled = true
      this.pageList = []
      this.queryParams.menuId = undefined
      this.menu = {}
      this.menuName = undefined
      this.menuType = undefined
    }
  }
}
</script>

<style scoped>
.perm-container {
  margin-bottom: 20px;
}
</style>

